package com.hontech.bread.ui.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.Fragment
import com.hontech.bread.R
import com.hontech.bread.app.runWithInit
import com.hontech.bread.device.ResetReplenishEvent
import com.hontech.bread.store.StoreCargo
import com.hontech.bread.store.StoreProduct
import com.hontech.bread.store.setProductImage
import com.hontech.bread.ui.dialog.DeliveryDialog
import com.hontech.bread.ui.dialog.hasPaying
import com.hontech.bread.ui.dialog.waitVerify
import com.hontech.bread.ui.parts.HeaderParts
import com.hontech.bread.ui.parts.PointsParts
import com.hontech.bread.utils.execIgnore
import com.hontech.bread.utils.log
import com.hontech.bread.utils.onClick
import com.hontech.bread.utils.priceFormat
import com.hontech.bread.utils.registerEvent
import com.hontech.bread.utils.runOnUiCatchAny
import com.hontech.bread.utils.setClickScaleAnimator
import com.hontech.bread.utils.unregister
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

private const val PAGE_WITH_NUM = 2

class Vend2Fragment : Fragment() {

    companion object {

        var vendFlag = false
            private set
    }

    private lateinit var mHeader: HeaderParts
    private lateinit var mBtnBack: Button
    private lateinit var mBtnNext: Button
    private lateinit var mPoints: PointsParts
    private lateinit var mItem0: Vend2Item
    private lateinit var mItem1: Vend2Item

    private var products = listOf<StoreProduct>()

    private var mPageIndex = 0
    private var mPageCount = 1

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_vend2, null)
        init(view)
        return view
    }

    private fun init(view: View) {
        mHeader = view.findViewById(R.id.id_vend2_header)
        mBtnBack = view.findViewById(R.id.id_vend2_btn_back)
        mBtnNext = view.findViewById(R.id.id_vend2_btn_next)
        mPoints = view.findViewById(R.id.id_vend2_points)
        mItem0 = Vend2Item(
            view,
            R.id.vend2_item0,
            R.id.id_item_bread_image0,
            R.id.id_item_bread_tv_price0,
            R.id.id_item_bread_tv_no_product0,
            R.id.id_item_bread_tv_name0
        )
        mItem1 = Vend2Item(
            view,
            R.id.vend2_item1,
            R.id.id_item_bread_image1,
            R.id.id_item_bread_tv_price1,
            R.id.id_item_bread_tv_no_product1,
            R.id.id_item_bread_tv_name1
        )

        mBtnBack.setOnClickListener { onClickBack() }
        mBtnNext.setOnClickListener { onClickNext() }
    }

    override fun onResume() {
        log("vend2 resume")
        super.onResume()
        registerEvent(this)
        runOnUiCatchAny { runWithInit { loadProduct() } }
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onResetReplenishEvent(event: ResetReplenishEvent) {
        runOnUiCatchAny { loadProduct() }
    }

    override fun onPause() {
        super.onPause()
        unregister(this)
    }

    private suspend fun onProductClick(product: StoreProduct) {

        execIgnore {
            val cargo = StoreCargo.queryNotEmptyInfo(product.productId)
            if (hasPaying()) {
                return
            }
            vendFlag = true
            val manager = waitVerify(product)
            cargo.clear()
            loadProduct()
            DeliveryDialog(product, cargo).delivery(manager)
        }
        vendFlag = false
    }

    private suspend fun loadProduct() {
        products = StoreProduct.query()
        updatePage()
    }

    private fun setPage(index: Int) {
        val p0 = products.getOrNull(index)
        if (p0 != null) {
            mItem0.setUp(p0, ::onProductClick)
        } else {
            mItem0.setNone()
        }

        val p1 = products.getOrNull(index + 1)
        if (p1 != null) {
            mItem1.setUp(p1, ::onProductClick)
        } else {
            mItem1.setNone()
        }
    }

    private fun updatePage() {
        log("product size:${products.size}")
        val max = ((products.size + PAGE_WITH_NUM - 1) / PAGE_WITH_NUM)
        mPageCount = if (max == 0) {
            1
        } else {
            max
        }
        log("page count:$mPageCount")
        mPageIndex = 0
        mPoints.count = mPageCount
        mPoints.index = mPageIndex
        setPage(0)
    }

    private fun onClickNext() {
        if ((mPageIndex + 1) >= mPageCount) {
            return
        }
        mPageIndex += 1
        setPage(mPageIndex * PAGE_WITH_NUM)
        mPoints.index = mPageIndex
    }

    private fun onClickBack() {
        if (mPageIndex <= 0) {
            return
        }
        mPageIndex -= 1
        setPage(mPageIndex * PAGE_WITH_NUM)
        mPoints.index = mPageIndex
    }
}

private class Vend2Item(
    bkView: View,
    itemId: Int,
    imageId: Int,
    priceId: Int,
    noId: Int,
    nameId: Int
) {

    private val view: View = bkView.findViewById<ConstraintLayout>(itemId)

    private val mTvName = view.findViewById<TextView>(nameId)
    private val mImage = view.findViewById<ImageView>(imageId)
    private val mPrice = view.findViewById<TextView>(priceId)
    private val mTvNo = view.findViewById<TextView>(noId)

    init {
        mImage.setClickScaleAnimator()
    }

    fun setNone() {
        view.visibility = View.INVISIBLE
    }

    @SuppressLint("SetTextI18n")
    fun setUp(product: StoreProduct, itemClick: suspend (StoreProduct) -> Unit) {
        view.visibility = View.VISIBLE

        mTvName.text = product.name
        mTvNo.setTag(R.id.imageId, product.productId)

        mPrice.text = priceFormat(product.price.toLong())
        mImage.setProductImage(product)

        mImage.onClick {

            try {
                if (update(product)) {
                    itemClick(product)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        runOnUiCatchAny { update(product) }
    }

    private suspend fun update(product: StoreProduct): Boolean {
        val ret = StoreCargo.queryIsNotEmpty(product.productId)

        if (mTvNo.getTag(R.id.imageId) != product.productId) {
            return false
        }

        if (ret) {
            mTvNo.visibility = View.INVISIBLE
        } else {
            mTvNo.visibility = View.VISIBLE
        }
        return ret
    }
}



















